import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import { isLogined } from "../utils/tools";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/cart",
    name: "Cart",
    component: () => import("../views/Cart.vue"),
    meta: {
      needLogin: true,
    },
  },
  {
    path: "/detail",
    name: "Detail",
    component: () => import("../views/Detail.vue"),
    meta: {
      hideTabbar: true,
    },
  },
  {
    path: "/list",
    name: "List",
    component: () => import("../views/List.vue"),
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/reg",
    name: "Reg",
    component: () => import("../views/Reg.vue"),
  },
  {
    path: "/submit_post",
    name: "submitPost",
    component: () => import("../views/submitPost.vue"),
    meta: {
      hideTabbar: true,
    },
  },
  {
    path: "/order",
    name: "Order",
    component: () => import("../views/MyOrder.vue"),
  },
  {
    path: "/orderdetail",
    name: "OrderDetail",
    component: () => import("../views/orderDetail.vue"),
  },
  {
    path: "/user",
    name: "User",
    component: () => import("../views/User.vue"),
    meta: {
      needLogin: true,
    },
  },
  {
    path: "/modipwd",
    name: "ModiPwd",
    component: () => import("../views/ModiPwd.vue"),
    meta: {
      needLogin: true,
    },
  },
  {
    path: "/modiinfo",
    name: "ModiInfo",
    component: () => import("../views/ModiInfo.vue"),
    meta: {
      needLogin: true,
    },
  },
  // 404
  {
    path: "*",
    name: "NotFound404",
    component: () => import("../views/NotFound404.vue"),
  },
];

const router = new VueRouter({
  routes,
});
// 前置全局守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.meta.needLogin) {
    //  判断是否登录了
    if (isLogined()) {
      next();
    } else {
      next({
        name: "Login",
      });
    }
  } else {
    next();
  }
});

export default router;
